package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"

	"github.com/antchfx/htmlquery"
	"github.com/gocolly/colly"
)

func Aikanhanman_sprider(work_name string, url string,sava_path string) {
	c1 := colly.NewCollector()
	c1.UserAgent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3"

	c2 := c1.Clone() // 二级页面

	var all_data []Man_hua_data // 漫画所有的数据

	//收到响应后
	c1.OnResponse(func(r *colly.Response) {
		doc, err := htmlquery.Parse(strings.NewReader(string(r.Body)))
		if err != nil {
			fmt.Println(err)
		}

		sectionsXpath := htmlquery.Find(doc, `//div[@class="catalog-box"]/div[@class="list-wrap"]/div[@class="catalog-list"]/ul[@class="clearfix"]/li`)
		for _, node := range sectionsXpath {
			next_url := htmlquery.FindOne(node, "//a")
			next_url_str := "https://www.aikanhanman.com" + htmlquery.SelectAttr(next_url, "href")
			// htmlquery.InnerText(next_url)
			r.Ctx.Put("next_url_str", next_url_str)
			c2.Request("GET", next_url_str, nil, r.Ctx, nil)
		}
	})

	// 二级页面
	c2.OnResponse(func(r *colly.Response) {
		doc, err := htmlquery.Parse(strings.NewReader(string(r.Body)))
		if err != nil {
			fmt.Println(err)
		}

		next_url_str := r.Ctx.Get("next_url_str")
		章节数据 := Man_hua_data{}
		章节数据.SectionUrl = next_url_str
		tmp1 := htmlquery.FindOne(doc, `//h1[@class="comic-name"]`)
		章节数据.SectionName = htmlquery.InnerText(tmp1)
		imgsXpath := htmlquery.Find(doc, `//main[@id="mainView"]/ul/li`)
		章节数据.ImgPage = 1
		for _, node := range imgsXpath {
			tmp2 := htmlquery.FindOne(node, `//img`)
			章节数据.PicturesUrls = append(章节数据.PicturesUrls, htmlquery.SelectAttr(tmp2, "src"))
		}
		all_data = append(all_data, 章节数据)
	})

	c1.Visit(url)
	c1.Wait()
	c2.Wait()
	// fmt.Println(all_data)

	data_txt, err := json.Marshal(all_data)
	if err != nil {
		fmt.Println(err)
		return
	}
	openFile, e := os.OpenFile(sava_path+work_name+".json", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if e != nil {
		fmt.Println(e)
		return
	}
	openFile.WriteString(string(data_txt))
	openFile.Close()
}
